package com.le.edu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.le.edu.domain.dto.SubjectDTO;
import com.le.edu.domain.entity.Subject;
import com.le.edu.domain.screen.PieVO;
import com.le.edu.listener.SubjectImportListener;
import com.le.edu.mapper.SubjectMapper;
import com.le.edu.service.SubjectService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 17447
 * @description 针对表【t_subject(课程科目)】的数据库操作Service实现
 * @createDate 2024-04-07 17:25:14
 */
@Service
@Slf4j
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject>
        implements SubjectService {

    @Cacheable(value = "subject", key = "#root.method.name", sync = true)
    @Override
    public List<Subject> listWithTree() {
        List<Subject> all = baseMapper.selectList(null);
        return all.stream()
                .filter(menu -> menu.getPid() == 0)
                .peek(menu -> menu.setChildren(getChildren(menu, all)))
                .sorted((Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort()))))
                .collect(Collectors.toList());
    }

    @CacheEvict(value = "subject", key = "'listWithTree'")
    @Override
    public String importData(MultipartFile file) {
        try {
            InputStream is = file.getInputStream();
            SubjectImportListener listener = new SubjectImportListener(this);
            EasyExcel.read(is, SubjectDTO.class, listener).sheet().doRead();
            return listener.getAnalysis();
        } catch (IOException e) {
            log.info("上传excel出错，{}", e.getMessage());
        }
        return null;
    }

    @Override
    public List<PieVO> computeCourseCountBySubject() {
        return baseMapper.computeCourseCountBySubject();
    }

    @Override
    public List<PieVO> computeSubjectCount() {
        return baseMapper.computeSubjectCount();
    }

    private List<Subject> getChildren(Subject root, List<Subject> all) {
        return all.stream()
                .filter(menu -> menu.getPid().equals(root.getSubjectId()))
                .peek(menu -> menu.setChildren(getChildren(menu, all)))
                .sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
                .collect(Collectors.toList());
    }
}




